from fastapi import APIRouter, Header, HTTPException, WebSocket, WebSocketDisconnect
from typing import Optional
from .models import OutHeart, OutWeather
from .sub_utils import MobileHeartBeat, TianXingApi, ConnectionManager
from ..curtain_control.routers import dbCurtain
from ..blob_control.routers import dbBlob
from ..fan_control.routers import dbFan
from ..door_control.routers import dbDoor
from ..oled_control.routers import dbOled
from ..data_views.sub_utils import DataViews
import threading
import time


def clearClockDevNum():
    while True:
        mobile_manager.clear_dev()
        time.sleep(10)


router = APIRouter(
    prefix="/SystemInfo",
    tags=['系统信息']
)

mobile_manager = MobileHeartBeat()
tianxingApi = TianXingApi()
dbData = DataViews()
# manager = ConnectionManager()
clockThread = threading.Thread(target=clearClockDevNum)
clockThread.setDaemon(True)
clockThread.start()


@router.get("/heart", response_model=OutHeart)
async def get_dev_num(user_agent: Optional[str] = Header(None)):
    # ms = round(time.time() - float(heart.time / 1000), 2) * 1000
    mobile_manager.push_dev(user_agent, now_time=time.time())
    dataDict = {
        'devNum': mobile_manager.len_mobile_connect(),
        'time': time.time(),
        'curtainControl': {
            'extraSpeed': dbCurtain.getExtraSpeed(),
            'openStatus': dbCurtain.getOpenStatus()
        },
        'blobControl': {
            'roomName': dbBlob.getRoomName(),
            'colorCode': dbBlob.getColorCode()
        },
        'fanControl': {
            'extraSpeed': dbFan.getExtraSpeed(),
            'openStatus': dbFan.getOpenStatus()
        },
        'doorControl': {
            'openStatus': dbDoor.getOpenStatus(),
            'inputPassword': dbDoor.getInputPassWord()
        },
        'oledControl': {
            'inputText': dbOled.getInputText()
        },
        'data': {
            'temperature': dbData.getTemperature(),
            'humidity': dbData.getHumidity(),
            'airquality': dbData.getAirQuality()
        }
    }
    return dataDict


@router.get("/EndHeart")
async def logout_dev():
    mobile_manager.clear_dev()
    return 'Ok!'


@router.get("/Weather", response_model=OutWeather)
async def get_weather():
    result = tianxingApi.getWeather('贵阳市')
    if result is None:
        raise HTTPException(status_code=410, detail='Api requests fault!')
    else:
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        for each in result['newslist']:
            # print(each)
            if each['date'] == now_date:
                return {'real': each['real'], 'img': each['weatherimg'], 'weather': each['weather']}
        raise HTTPException(status_code=412, detail='Api data handle fault!')


# @router.websocket("/heart")
# async def heart_pack(web_socket: WebSocket):
#     await manager.connect(web_socket)
#     try:
#         while True:
#             last_time = time.time()
#             await manager.send_data("it's a heart beat", web_socket)
#             res = await manager.recv_data(web_socket)
#             now_time = time.time()
#             print(f"[{web_socket.headers}] is {now_time - last_time} s delay")
#     except WebSocketDisconnect:
#         manager.disconnect(web_socket)
